package main

import (
	"flag"
	"fmt"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/common"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/config"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/handler"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/svc"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/vxopen-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf, rest.WithCors("*"))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	// 额外添加 ws 的句柄
	// 放在 internal/handler/routes.go 下会被 goctl 给刷掉
	server.AddRoute(
		rest.Route{
			Method: http.MethodGet,
			Path:   ctx.Config.Websocket.Chat,
			Handler: func(w http.ResponseWriter, r *http.Request) {
				ctx.WSChatHub.HandleWebSocket(w, r)
			},
		})
	server.AddRoute(
		rest.Route{
			Method: http.MethodGet,
			Path:   ctx.Config.Websocket.Dashboard,
			Handler: func(w http.ResponseWriter, r *http.Request) {
				ctx.WSDashboardHub.HandleWebSocket(w, r)
			},
		})

	httpx.SetErrorHandler(func(err error) (int, any) {
		switch e := err.(type) {
		case *common.CodeError:
			return http.StatusOK, e.Data()
		default:
			return http.StatusOK,
				common.NewCodeError(http.StatusInternalServerError, e.Error()).(*common.CodeError).Data()
		} // TODO：正则提取具体错误内容
	})

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
